import React, { Component } from 'react';
import { Tabs, Button,Table ,Divider,Modal ,Form,Input,Select, Drawer,  Tree} from 'antd';
import '@/assets/css/settings';
import * as APIService from '../../axios/api';
import * as utils from '../../utils_yyr/action';
const { TabPane } = Tabs;
const { Option } = Select;
const { confirm } = Modal;
const { TreeNode } = Tree;

var keys=[];
 class App extends Component {
	state = { loading: false, dataSource: [], visible: false,
	modalData:'',//选中的数据
    handleType:0,//新增0 修改1
	topId:0,
	options:[],
	drawer:false,
	treeData: [],
	checkedKeys: '',
	expandedKeys:[],
	key:1,
	authData:[],
 };
	componentDidMount() {
		this.fetch();
		this.getMenusList(this.state.key)
	}
	getMenusList=(key)=>{
		APIService.getMenus(key).then(data=>{
			const dataSource=data.data.data;
				this.setState({
						treeData:dataSource
					})
				})
	}
	//初始化加载数据
	fetch=()=>{
		this.setState({loading:true})
		APIService.getRoles().then(data=>{
			const dataSource=data.data.data.data;
		            this.setState({
						dataSource:dataSource,
						loading:false,
					})
				  })
				  
				  
	}
	getRoleMenuList=(id,type)=>{
		APIService.queryRoleMenuList(id,type).then(dataSource=>{
			this.setState({
				authData:dataSource.data.data
			  },()=>this.defalutKeys(this.state.authData));
		})
	}
	handleChangeTab = key => {
		if (parseInt(key) === 1) {
			this.setState({key})
			this.getMenusList(key);
			this.getRoleMenuList(this.state.modalData.roleId,key);
			
		} else if (parseInt(key) === 2) {
			this.setState({key})
			this.getMenusList(key)
			this.getRoleMenuList(this.state.modalData.roleId,key);
		}
		else if (parseInt(key) === 3) {
			this.setState({key})
			this.getMenusList(key)
			this.getRoleMenuList(this.state.modalData.roleId,key);
		}
	};

	//添加修改角色提交
    submitMenu=(e)=>{
		this.props.form.validateFields((err, values) => {
			if (!err) {

				if(this.state.handleType===0){
					values=Object.assign({}, values,{creatorId:parseInt(localStorage.getItem('userId'))} )
				}else{
					values=Object.assign({}, values,{updaterId:parseInt(localStorage.getItem('userId')),id:this.state.modalData.roleId})
				}
                const that=this;
				APIService.addOrUpdateRole(values).then(data=>{
					if(data.data.code===200){
						utils.openNotification('success', '操作成功')
					}else{
						utils.openNotification('warning', data.data.msg)
					}
					that.handleCancel();
					that.props.form.resetFields();
				  	that.fetch();
				 })
				
			} else {
				console.log(err);
			}
		});
	}

	//权限配置提交
    submitSettings=(e)=>{
				const that=this;
				const values={buttonIdList:this.state.checkedKeys.btnkeys,menuIdList:this.state.checkedKeys.menukeys,creatorId:parseInt(localStorage.getItem('userId')),roleId:this.state.modalData.roleId,type:parseInt(this.state.key)}
				APIService.authorityDeploy(values).then(data=>{
					if(data.data.code===200){
						utils.openNotification('success', '操作成功')
					}else{
						utils.openNotification('warning', data.data.msg)
					}
					that.handleCancel();
				  	that.fetch();
				 })
	}


   //弹出删除框
   showDeleteConfirm = (data) => {
	const that = this;
	confirm({
		title: '确认删除' + '[' + data.roleName + ']？',
		okText: '确认',
		okType: 'danger',
		cancelText: '取消',
		onOk() {
				APIService.deleteRole(data.roleId).then(data => {
					utils.openNotification('success', '删除成功');
					that.fetch();
				}).catch(function (error) {
					utils.openNotification('error', error.message);
				});	
				
			

		},
		onCancel() {
			console.log('Cancel');
		},
	});
}

    //0新增  1修改
	showModal = (data,type) => {
		if(type===1){
			this.props.form.setFieldsValue({
				name: data.roleName,
				code:data.roleCode,
				description:data.description
			})
		}
		this.setState({
			visible: true,
			modalData:data,
			handleType:type,
		  });
		
	  };
   
	showDrawer = (data) => {
		keys=[];
		this.getRoleMenuList(data.roleId,this.state.key);
			this.setState({
				drawer: true,
				modalData:data,
			  });
	  };
	  defalutKeys=(data)=> {
		
				data.map(item => {
					
					if(item.children===undefined){
						
						keys.push(`btnId:${item.id}`)
					}else if (item.children.length>0) {
						
						return (
								this.defalutKeys(item.children)
						);
					}else if(item.children.length===0&&item.sysMenuButtonList.length>0){
						
					return (
						this.defalutKeys(item.sysMenuButtonList)
					);
					}else if(item.children.length===0&&item.sysMenuButtonList.length===0){
						keys.push(`menuId:${item.id}`)
					}
					
				});
				console.log(keys);
				this.setState({
					expandedKeys:keys
				})
	  }
	
	  handleCancel = e => {
		this.props.form.resetFields();
		this.setState({
		  visible: false,
		  drawer:false,
		});
	  };
     //节点加载完毕时触发
	//   onLoadData = treeNode =>
	//   new Promise(resolve => {
	// 	  if (treeNode.props.children) {
	// 		  resolve();
	// 		  return;
	// 	  }
	// 	  setTimeout(() => {
	// 		treeNode.props.dataRef.children = [
	// 		  { title: 'Child Node', key: `${treeNode.props.eventKey}-0` },
	// 		  { title: 'Child Node', key: `${treeNode.props.eventKey}-1` },
	// 		];
	// 		this.setState({
	// 		  treeData: [...this.state.treeData],
	// 		});
	// 		resolve();
	// 	  }, 1000);
	//   });
  //生成树
  renderTreeNodes = data =>
	  data.map(item => {
		  if(item.children===undefined){
			return <TreeNode  title={item.buttonName} key={`btnId:${item.id}`} {...item} dataRef={item} selectable />;
		  }
		  if (item.children.length>0) {
			 
			  return (
				  <TreeNode title={item.name} key={`menuId:${item.id}`} dataRef={item} selectable>
					  {this.renderTreeNodes(item.children)}
				  </TreeNode>
			  );
		  }else if(item.children.length===0&&item.sysMenuButtonList.length>0){
			return (
				<TreeNode title={item.name} key={`menuId:${item.id}`} dataRef={item} selectable>
					{this.renderTreeNodes(item.sysMenuButtonList)}
				</TreeNode>
			);
		  }else{
			return <TreeNode  title={item.name} key={`menuId:${item.id}`} {...item} dataRef={item} selectable />;
		  }
		 
	  });
      //权限框选中事件
	  onCheck =( checkedKeys,e) => {
		var menukeys=[];
		var btnkeys=[];
		for(var key of checkedKeys){
           if(key.indexOf('menuId')){
			btnkeys.push(parseInt(key.substring(key.indexOf(':')+1)));
		   }else{
			menukeys.push(parseInt(key.substring(key.indexOf(':')+1)));
		   }
		}
		//halfCheckedKeys 有关联的父级值
		for(var key2 of e.halfCheckedKeys){
			 menukeys.push(parseInt(key2.substring(key2.indexOf(':')+1)));
		 }
         this.setState({ checkedKeys:{btnkeys:btnkeys,menukeys:menukeys},expandedKeys: checkedKeys});
	  };

	render() {
		const columns = [
			{
				title: '序号',
				width: '10%',
				render:(text,record,index)=> `${index+1}`,
			  },
		
			{
			  title: '角色编码',
			  dataIndex: 'roleCode',
			},
			{
			  title: '角色名称',
			  dataIndex: 'roleName',
			},
			{
			  title: '描述',
			  dataIndex: 'description',
			},
			{
                title: '操作',
                width:'12%',
				render: (text, record) => {
					return	<span>
					  <a onClick={()=>this.showModal(record,1)}>修改</a>
					  <Divider type="vertical" />

					  <a  onClick={()=>this.showDrawer(record)}>权限配置</a>
					  <Divider type="vertical" />
					  <a  onClick={()=>this.showDeleteConfirm(record)}>
						删除
					  </a>
					</span>
			}
		}
		  ];

		
		 const { getFieldDecorator } = this.props.form;
	

		const formItemLayout_addMenu = {
			labelCol: {
				sm: { span: 8 }
			},
			wrapperCol: {
				sm: { span: 9 }
			}
        };
        
			var operations = <div className="mydiv" > <Button icon="plus" onClick={()=>this.showModal([],0)} type="primary" > 新增 </Button></div >
		return (
			<div className="shadow-radius">
				<Tabs tabBarExtraContent={operations} defaultActiveKey="1" onChange={this.handleChangeTab}>
					<TabPane tab="角色管理" key="1">
					<Table columns={columns} rowKey={(record)=>record.roleId}  scroll={{y:500}}  dataSource={this.state.dataSource} pagination={false} loading={this.state.loading}  />
					</TabPane>
					
				</Tabs>
				
				<Modal
				width='600px'
				title="新增/修改"
				visible={this.state.visible}
				centered
				onOk={this.submitMenu}
				onCancel={this.handleCancel}
				okText="保存"
				cancelText="取消"
				>
					<Form {...formItemLayout_addMenu}>
					<Form.Item label="角色编码">
						{getFieldDecorator('code', {
							rules: [{ required: true, message: '请填写角色编码！' }]
						})(<Input />)}
					</Form.Item>
					<Form.Item label="角色名称">
						{getFieldDecorator('name', {
							rules: [{ required: true, message: '请填写角色名称！' }]
						})(<Input />)}
					</Form.Item>
                    <Form.Item label="描述">
						{getFieldDecorator('description')(<textarea style={{width:'100%',height:'4rem'}} />)}
					</Form.Item>
				
				</Form>

				</Modal>

				
				 <Drawer title="权限配置" placement="right" closable={true} onClose={this.handleCancel} visible={this.state.drawer}
                    width='600px' >

					<Tabs defaultActiveKey="1" onChange={this.handleChangeTab}>
									<TabPane tab="管理端" key="1">
									<Tree multiple checkedKeys={this.state.expandedKeys} checkable onCheck={this.onCheck}>
																{this.renderTreeNodes(this.state.treeData)}
														</Tree>
									</TabPane>
									<TabPane tab="移动端" key="2">
									<Tree multiple checkedKeys={this.state.expandedKeys} checkable onCheck={this.onCheck}>
																{this.renderTreeNodes(this.state.treeData)}
														</Tree>
									</TabPane>
									<TabPane tab="平板端" key="3">
									<Tree multiple checkedKeys={this.state.expandedKeys} checkable onCheck={this.onCheck}>
																{this.renderTreeNodes(this.state.treeData)}
														</Tree>
									</TabPane>
								</Tabs>


					<div
						style={{
						position: 'absolute',
						right: 0,
						bottom: 0,
						width: '100%',
						borderTop: '1px solid #e9e9e9',
						padding: '10px 16px',
						background: '#fff',
						textAlign: 'right',
						}}
					>
						<Button onClick={this.handleCancel} style={{ marginRight: 8 }}>
						取消
						</Button>
						<Button type='primary' onClick={this.submitSettings} style={{ marginRight: 8 }}>
						保存
						</Button>
					</div>
                </Drawer >
			

				
			</div>
		);
	}
}
export default Form.create()(App);